<template>
	<view class="map-box">
		<view class="page-body">
			<view class="page-section">
				<map id="myMap" style="width: 100%; height: 100vh;" :latitude="state.latitude" :longitude="state.longitude" show-location :polyline="useRunInfoData.isRuning ? useRunInfoData.runPolyline : state.polyline"
                :dottedLine="true" :show-scale="true">
        <cover-view class="back-box" :style="{top: (useAppData.titleHeight+3) + 'px'}" @tap="gotoBack">
          <cover-image v-if="initStatus" class="back-img" src="../../static/icon-back.png"></cover-image>
        </cover-view>
        <!-- <cover-image v-if="isShowCountdown" class="countdown" src="../../static/countdown.gif"></cover-image> -->
        <CountDown></CountDown>
        <PromptSpeech></PromptSpeech>
				</map>
			</view>
<!--      <button class="save-pdf" @tap="drawMapAndPolylineOnCanvas">保存图片</button>-->
      <BottomDrawer ref="bottomDrawerRef"></BottomDrawer>
		</view>
    <cover-view class="mask" v-if="state.tipAuth">
      <cover-image class="image-tip" src="https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/tanchuang.png"></cover-image>
      <cover-view class="btn" @tap="hideTipAuth">我知道了</cover-view>
    </cover-view>
    <canvas canvas-id="mapCanvas" style="position: absolute; bottom: -10000px;width: 375px; height: 882px;"></canvas>
    <uni-popup ref="alertDialogRangeRef" type="dialog" v-if="state.isShowPop">
      <uni-popup-dialog
        :cancelText="state.cancelText"
        :confirmText="state.confirmText"
        :content="state.content"
        @close="handleClose"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>
<script setup>
import {onLoad, onShow, onHide, onUnload, onShareAppMessage, onShareTimeline} from "@dcloudio/uni-app";
import {ref, reactive, watch, onMounted, nextTick} from "vue"
import * as API from "../../api/api.js"
import * as util from "../../utils/util"
import BottomDrawer from "../components/bottomDrawer"
import PromptSpeech from "../components/promptSpeech"
import CountDown from "../components/countDown"
import { storeToRefs } from "pinia";
import { useAppStore } from "../../store/app";
import { useRunInfoStore } from "../../store/runInfo";
import { useShareStore } from "../../store/share";
import { useChatStore } from "../../store/chat"
import {getOssSign, updatePathImg} from "../../api/api.js";
import { userLoginStore } from "../../store/userLogin";
const useShareData = useShareStore()
const useRunInfoData = useRunInfoStore()
const useAppData = useAppStore()
const useChatData = useChatStore()
const userLoginData = userLoginStore()
const { coordinate, isShowCountdown, initStatus, runType, centerPosition, totalSeconds, matchSpeed, sportRange, runMileage, recordEnd, runUuid } = storeToRefs(useRunInfoData)
const {userInfo} = storeToRefs(userLoginData)

const alertDialogRef = ref(null);
const alertDialogRangeRef = ref(null);
const url = import.meta.env.VITE_APP_API_BASE_URL
const uploadUrl = import.meta.env.VITE_UPLODA_URL
const state = reactive({
  tipAuth: false,
  proportionvc: 0.5,//抽屉初始显示的位置，内容的百分比
  handleHeight: 20,//抽屉顶部边框高度，可以设置0，隐藏
  coordinates: {},
  showMap: false,
  id: 0, // 使用 marker点击事件 需要填写id
  title: 'map',
  // latitude: 39.558761,
  // longitude: 116.731953,
  latitude: 39.555118272569445,
  longitude: 116.72717800564236,
  polyline: [{
    points: [],
    color: "#FF0000DD",
    width: 8,
    dottedLine: false,
    arrowLine: false
  }],
  polyline1: [{
    points: [],
    color: "#FF0000DD",
    width: 8,
    dottedLine: false,
    arrowLine: false
  }],
  // contentAuth: "为确保手机息屏后也能获取到跑步轨迹，请先设置位置为“使用小程序时和离开后允许”再开始跑步",
  timerInterval: null,
  runMileage: 0,
  allMileage: 0,
  itemSpeed: 0,
  cancelText: "确认",
  content: "不在跑步范围内，请回到体育场内。",
  confirmText: "",
  isShowPop: false,
  prePage: null,
  autoRun: false,
  centerDistance: 0,
  zoom: 18,
  scale: 2,
  trajectoryUrl: '',
  userInfo: {},
})

const bottomDrawerRef = ref(null)

onShareAppMessage((res) => {
  return useShareData.shareInfo
})
onShareTimeline((res) => {
  return useShareData.shareInfo
})

const gotoBack = () => {
  uni.navigateTo({
    url: state.prePage
  });
}
const capturedMapImage = ref('');
const canvasWidth = ref(375)  // Canvas宽度
const canvasHeight = ref(700) // Canvas高度
// 获取静态地图的 URL
const getStaticMapUrl = (latitude, longitude, width, height) => {
  const scale = 1 // 高清图片
  const key = 'OZQBZ-WDY6Z-EPFXB-TBLPK-ITRAK-77FWI'; // 替换为你的腾讯地图 API Key
  const mapUrl = `https://apis.map.qq.com/ws/staticmap/v2/?center=${latitude},${longitude}&zoom=${state.zoom}&size=${width}*${height}&scale=${scale}&key=${key}`
  return mapUrl
}
// 加载图片
const loadImage = (url) => {
  return new Promise((resolve, reject) => {
    console.log(url, 3333333333333333)
    uni.getImageInfo({
      src: url,
      success: (res) => {
        resolve(res.path)
      },
      fail: (err) => {
        console.error('下载地图图片失败:', err)
        reject(err)
      }
    })
  })
}

// 保存 Canvas 为图片
const saveMapAsImage = () => {
  uni.canvasToTempFilePath({
    canvasId: 'mapCanvas',
    success: (res) => {
      console.log(res.tempFilePath, '临时路径=====================')
      uploadImage(res.tempFilePath)
      // saveImage(res.tempFilePath)
    },
    fail(err) {
      console.error('Canvas 保存为图片失败:', err)
    }
  })
}

// 保存图片到相册
// const saveImage = (filePath) => {
//   uni.saveImageToPhotosAlbum({
//     filePath,
//     success() {
//       uni.showToast({ title: '保存成功', icon: 'success' })
//     },
//     fail(err) {
//       console.error('保存图片到相册失败:', err)
//       if (err.errMsg.includes('auth deny') || err.errMsg.includes('auth denied')) {
//         uni.showModal({
//           title: '提示',
//           content: '需要您授权保存图片到相册，是否打开设置？',
//           success(res) {
//             if (res.confirm) {
//               uni.openSetting()
//             }
//           }
//         })
//       }
//     }
//   })
// }
// 图片上传
const uploadImage = (filePath) => {
  console.log(filePath, '临时路径参数----------------')
  getOssSign(encodeURIComponent(`${runUuid.value}.png`)).then(res => {
    if (res.code === 0) {
      let count = 10
      let tipCount = 10
      let tipTime = null
      const time = setInterval(() => {
        count--
        if (count <= 0) {
          count = 10
          clearInterval(time)
          uni.showModal({
            title: '提示',
            content: '网络异常或GPS信号差，轨迹生成失败',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定');
                updatePathImgFun('')
              } else if (res.cancel) {
                console.log('用户点击取消');
              }
            }
          });
          tipTime = setInterval(() => {
            tipCount--
            if (tipCount <= 0) {
              tipCount = 10
              clearInterval(tipTime)
              updatePathImgFun('')
            }
          }, 1000)
        }
      }, 1000)
      uni.uploadFile({
        url: uploadUrl, // 替换为你的服务器地址
        filePath: filePath,                       // 上传的文件路径
        name: 'file', // 后端接收文件的参数名
        formData: {
          key: res.data.key,
          policy: res.data.policy,
          OSSAccessKeyId: res.data.accessId,
          signature: res.data.signature,
          success_action_status: "200",
          // 'x-oss-security-token': securityToken // 使用STS签名时必传。
        },
        success: (uploadFileRes) => {
          console.log('---上传成功:', uploadFileRes)
          // 处理服务器响应
          // if (uploadFileRes.statusCode === 200) {
          //   const data = JSON.parse(uploadFileRes.data)
          //   console.log('服务器响应数据:', data)
          //   state.trajectoryUrl = data.data
          //   updatePathImgFun(data.data)
          // } else {
          //   console.error('上传失败，状态码:', uploadFileRes.statusCode)
          // }
        },
        fail: (err) => {
          console.error('上传失败:', err)
        },
        complete: (uploadFileRes) => {
          clearInterval(time)
          clearInterval(tipTime)
          console.log(uploadFileRes, 22222222)
          // let url = filePath
          // if (uploadFileRes.statusCode === 200) {
          //   // const data = JSON.parse(uploadFileRes.data)
          //   // console.log('服务器响应数据:', data)
          //   // url = data.data
          // } else {
          //   console.error('上传失败，状态码:', uploadFileRes.statusCode)
          // }
          updatePathImgFun(`${runUuid.value}.png`)
        }
      })
    }
  })
}

const updatePathImgFun = (pathUrl) => {
  console.log()
  updatePathImg({
    userId: state.userInfo?.customers?.customerId,
    uuid: runUuid.value,
    pathImg: pathUrl
  }).then(response => {
    console.log('/healthbot-sport/mileage/updatePathImg',  response, 222222222222222)
    uni.hideLoading();
    if (response.code === 0) {
      uni.showToast({ title: '地图已生成，请在“里程记录”中，选择查看', icon: 'none' })
      setTimeout(() => {
        uni.redirectTo({
          url: "/examPages/record/achievements",
        });
      }, 1500)
    }
    if (bottomDrawerRef.value) {
      bottomDrawerRef.value.callChildMethod()
    }
  }, err => {
    console.log(err, 333333333333333)
  })
}

const calculateDegreePerPixel = (zoom) => {
  const earthCircumference = 40075016.686 // 地球周长，单位：米
  const mapWidthInMeters = earthCircumference * Math.cos(centerPosition.value.latitude * Math.PI / 180) / Math.pow(2, zoom)
  const lngPerPx = mapWidthInMeters / canvasWidth.value // 每个像素代表的经度
  const latPerPx = earthCircumference / Math.pow(2, zoom + 8) // 每个像素代表的纬度

  return { lngPerPx, latPerPx }
}


// 在 Canvas 上绘制地图和轨迹
async function drawMapAndPolylineOnCanvas() {
  uni.showLoading({
    title: '运动轨迹上传中...',
    mask: true
  })
  const ctx = uni.createCanvasContext('mapCanvas')

  // 获取静态地图图片
  console.log(centerPosition.value, '中心点坐标-=======================')
  const mapUrl = getStaticMapUrl(centerPosition.value.latitude, centerPosition.value.longitude, canvasWidth.value, canvasHeight.value)
  // 加载图片
  const image = await loadImage(mapUrl)
  // 绘制地图
  ctx.drawImage(image, 0, 0, canvasWidth.value, canvasHeight.value)
  if (state.polyline && state.polyline.length) {
    let arr = []
    console.log(state.polyline, '初始轨迹数据----------------------')
    state.polyline.forEach(val => {
      arr.push(...val.points)
    })
    console.log(arr, '合并后的轨迹数据-----------------')
    if (arr.length) {
      // 测试数据用polyline1, 在模拟器上使用没有模拟数据，发布上线需要改成polyline
      // 将经纬度转换为 Canvas 坐标
      // const degreePerPixel = calculateDegreePerPixel(state.zoom)
      // const canvasPoints = arr.map((point) => {
      //   return {
      //     x: ((point.longitude - centerPosition.value.longitude) / degreePerPixel.lngPerPx) * canvasWidth.value + canvasWidth.value / 2,
      //     y: ((centerPosition.value.latitude - point.latitude) / degreePerPixel.latPerPx) * canvasHeight.value + canvasHeight.value / 2
      //   }
      // })
      const canvasPoints = arr.map((point) => {
        return {
          x: ((point.longitude - centerPosition.value.longitude) / 0.02) * canvasWidth.value + canvasWidth.value / 2,
          y: ((centerPosition.value.latitude - point.latitude) / 0.02) * canvasHeight.value + canvasHeight.value / 2
        }
      })
      // 绘制轨迹
      ctx.beginPath()
      ctx.moveTo(canvasPoints[0].x, canvasPoints[0].y)
      for (let i = 1; i < canvasPoints.length; i++) {
        ctx.lineTo(canvasPoints[i].x, canvasPoints[i].y)
      }
      ctx.setStrokeStyle('#3D5FFD')
      ctx.setLineWidth(6)
    }
  }
  ctx.stroke()
  // 将内容绘制到 Canvas 上
  ctx.draw()
  saveMapAsImage()
}

watch(() => recordEnd.value,  (newPro, oldPro) => {
  console.log(newPro, 90000000000000000)
  if (newPro) {
    drawMapAndPolylineOnCanvas()
  }
})

onLoad((options) => {
  console.log("地图onLoad", options, useRunInfoData.isRuning,initStatus.value, state.polyline)
  if (!useRunInfoData.isRuning) {
    console.log("onload-地图",useRunInfoData.isRuning,initStatus.value, state.polyline)
    useChatData.setAllContent("")
    state.prePage = options.prePage || "/pages/chat/chat"
    state.polyline = [{
      points: [],
      color: "#FF0000DD",
      width: 8,
      dottedLine: false,
      arrowLine: false
    }]
    state.runMileage = 0
    useRunInfoData.setProportionShow(0.7);
    useRunInfoData.setInitStatus(true);
  } else {
    uni.showToast({
      title: "正在运动中，请稍后尝试～",
      icon: "none"
    })
    state.polyline = useRunInfoData.runPolyline
    state.runMileage = runMileage.value
    console.log("已跑坐标", useRunInfoData.runPolyline)
  }
  // uni.getSystemInfo({
  //   success: (res) => {
  //     this.setData({
  //       screenWidth: res.screenWidth,
  //       screenHeight: 400 // 地图高度设为400px
  //     });
  //   }
  // });
  // 绘制轨迹测试数据
  // wx.request({
  //   //地图WebserviceAPI驾车路线规划接口 请求路径及参数（具体使用方法请参考开发文档）
  //   url: 'https://apis.map.qq.com/ws/direction/v1/driving/?key=OZQBZ-WDY6Z-EPFXB-TBLPK-ITRAK-77FWI&from=39.894772,116.321668&to=39.902781,116.427171',
  //   success(res) {
  //     console.log(res, 3333333333)
  //     var result = res.data.result
  //     var route = result.routes[0]
  //
  //     var coors = route.polyline, pl = [];
  //     //坐标解压（返回的点串坐标，通过前向差分进行压缩）
  //     var kr = 1000000;
  //     for (var i = 2; i < coors.length; i++) {
  //       coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
  //     }
  //     //将解压后的坐标放入点串数组pl中
  //     for (var i = 0; i < coors.length; i += 2) {
  //       pl.push({latitude: coors[i], longitude: coors[i + 1]})
  //     }
  //     state.latitude = pl[0].latitude
  //     state.longitude = pl[0].longitude
  //     // 绘制路线
  //     state.polyline1 = [{
  //       points: pl,
  //       color: '#58c16c',
  //       width: 6,
  //       borderColor: '#2f693c',
  //       borderWidth: 1
  //     }]
  //   }
  // })
})

onShow(() => {
  console.log("onShow地图", initStatus.value, state.polyline, state.runMileage)
  state.userInfo = uni.getStorageSync("userInfo") ? JSON.parse(uni.getStorageSync("userInfo")) : null
  if(!useRunInfoData.isRuning) {
    if (initStatus.value) {
      console.log("重置")
      state.polyline = [{
        points: [],
        color: "#FF0000DD",
        width: 8,
        dottedLine: false,
        arrowLine: false
      }]
      state.latitude = 39.555118272569445
      state.longitude = 116.72717800564236
      state.runMileage = 0
      useRunInfoData.setRunMileage(0)
      useRunInfoData.setCenterDistance(0)
      useRunInfoData.setMatchSpeed(`0'00"`)
      useRunInfoData.setTimerNum("0.00")
      useRunInfoData.setTotalSeconds(0)
      useRunInfoData.setRecordEnd(false)
    }
  }
  uni.getSetting({
    success(res) {
      if(!res.authSetting['scope.userLocationBackground']) {
        state.tipAuth = true
      } else {
        if (initStatus.value) {
          useRunInfoData.setIsClickStartRun(true)
          useChatData.getRobotMsg({timeType: 0, uuid: null})
        }
      }
    }
  })
  useRunInfoData.getConfigList()
})

onHide(() => {
  console.log("地图页面隐藏")
})

onUnload(() => {
  console.log("地图页面卸载")
  //清除定时器
  useRunInfoData.clearCountDownTimer()
})

const hideTipAuth = () => {
  state.tipAuth = false
  useRunInfoData.setIsClickStartRun(false)
  useRunInfoData.startTask('start', false).then(res => {
    console.log("授权成功")
    useRunInfoData.setIsClickStartRun(true)
    useChatData.getRobotMsg({timeType: 0, uuid: null})
  }).catch(err => {
    useRunInfoData.setIsClickStartRun(true)
    console.log("授权失败")
  })
}

const handleClose = () => {
  state.isShowPop = false
}

const handleRange = (rangeNum) => {
  if (rangeNum && (Number(rangeNum) * 1000) > sportRange.value) {
    console.log("不在跑步范围内", state.isShowPop);
    if (state.isShowPop) return
    state.isShowPop = true
    state.autoRun = false
    setTimeout(() => {
      // state.cancelText = "确认";
      // state.content = "不在跑步范围内";
      // state.confirmText = "";
      useRunInfoData.stopCountDown()
      useRunInfoData.setRunType("suspend")
      alertDialogRangeRef?.value?.open()
    }, 300)
  } else {
    console.log("在跑步范围内");
    state.isShowPop = false
    state.autoRun = true
    useRunInfoData.setRunType("reStart");
    alertDialogRangeRef?.value?.close();
    // useRunInfoData.positiveTiming()
  }
}


const handleKm = (data, time) => {
  console.log("开始处理数据", time)
  let centerDistance = useRunInfoData.getMapDistance(centerPosition.value.latitude, centerPosition.value.longitude, data.latitude, data.longitude)
  console.log("距离中心点的距离", centerDistance)
  handleRange(centerDistance)
  useRunInfoData.setCenterDistance(centerDistance)
  setTimeout(() => {
    if (Number(centerDistance) * 1000 <= sportRange.value) {
      const prePosition = uni.getStorageSync("prePosition") ? JSON.parse(uni.getStorageSync("prePosition")) : null
      let itemDistance = 0
      let itemDuration = 0
      if (prePosition) {
        let preLatitude = prePosition.latitude
        let preLongitude = prePosition.longitude
        itemDuration = (new Date().getTime() - prePosition.second) / 1000 // 秒
        console.log("3秒前", itemDuration)
        // if (itemDuration >= 3) {
          console.log("3秒后---有效点", itemDuration)
          itemDistance = useRunInfoData.getMapDistance(preLatitude, preLongitude, data.latitude, data.longitude) // 公里
          console.log("itemDistance全值-公里", itemDistance)
          state.itemSpeed = itemDuration > 0 ? itemDistance/itemDuration : 0
          console.log("速度", state.itemSpeed)
          if(state.itemSpeed <= 0.015) {
            console.log("速度小于30米-公里", state.itemSpeed)
            // 绘制轨迹
            console.log("轨迹刚刚绘制前", state.polyline, data.latitude, data.longitude)
            let len = state.polyline.length - 1
            state.polyline[len].points.push({
              latitude: data.latitude,
              longitude: data.longitude
            })
            console.log("轨迹刚刚绘制完成", state.polyline)
            // let runDuration = (Number(totalSeconds.value)/60).toFixed(2) // 分钟
            console.log("this.runMileage===1111加前-公里", state.runMileage)
            // 总里程计算
            let intervalDistance = itemDistance.toFixed(3)
            state.runMileage = Number(state.runMileage) + Number(itemDistance) // 公里
            console.log("this.runMileage===222加后-公里", state.runMileage)
            console.log("一小段距离的数据-上、下经纬度、小段距离", preLatitude, preLongitude, data.latitude, data.longitude, itemDistance)
            console.log("跑的总公里", state.runMileage)
            // console.log("跑的总时长-分", runDuration)
            // 更新里程
            let allDistance = state.runMileage.toFixed(3)
            let allTime = Number(totalSeconds.value)
            // let intervalDistance = itemDistance.toFixed(3)
            let intervalDuration = Number(itemDuration)
            console.log("更新里程的参数---总", allDistance, allTime, intervalDistance, intervalDuration)
            state.allMileage = allDistance
            useRunInfoData.setRunMileage(state.runMileage.toFixed(3))
            useRunInfoData.onUpdateMileage(allTime, allDistance, intervalDistance, intervalDuration, data.latitude, data.longitude, data.speed, data.accuracy)
          } else {
            console.log("速度大于30米")
          }
        // }
      }
      if (!prePosition || (prePosition && itemDistance >= 0)) {
        uni.setStorageSync("prePosition", JSON.stringify({
          latitude: data.latitude,
          longitude: data.longitude,
          second: new Date().getTime()
        }));
      }
    }
  }, 10)
}

watch(() => runType.value, (newValue, oldValue) => {
  console.log("runType.value", newValue, state.polyline)
  if (newValue === "start") {
    state.polyline = [{
      points: [],
      color: "#FF0000DD",
      width: 8,
      dottedLine: false,
      arrowLine: false
    }]
  }
  if (newValue === "reStart") {
    state.polyline.push({
      points: [],
      color: "#FF0000DD",
      width: 8,
      dottedLine: false,
      arrowLine: false
    })
  }
  console.log("state.polyline=====0000", state.polyline)
})

// coordinate.value

watch(() => coordinate.value, (newValue, oldValue) => {
  console.log("99999999", state.allMileage, state.runMileage, runMileage.value)
  console.log("state.polyline---分段路线前-字符串", JSON.stringify(coordinate.value), JSON.stringify(newValue), JSON.stringify(oldValue))
  console.log("state.polyline---分段路线前", coordinate.value, state.polyline, newValue, oldValue, runMileage.value, state.runMileage)
  state.runMileage = runMileage.value
  if (state.polyline.length > 0) {
    let time = new Date().getTime()
    handleKm({
      latitude: newValue.latitude,
      longitude: newValue.longitude,
      speed: newValue.speed,
      accuracy: newValue.accuracy
    }, time)
    console.log("分段路线", state.polyline, time)
    useRunInfoData.setPolyline(state.polyline)
  }
  state.latitude = newValue.latitude
  state.longitude = newValue.longitude
}, {imediate: true})

watch(() => state.autoRun, (newValue, oldValue) => {
  console.log("自动跑入范围内开始计时", newValue)
  if (newValue) {
    useRunInfoData.positiveTiming()
  }
})

</script>
<style lang="scss" scoped>
.map-box{
  overflow: hidden;
}
.page-body {
  position: relative;
  overflow: hidden;
  .page-section{
    overflow: hidden;
  }

  .controls {
    width: 100vh;
    position: absolute;
    bottom: 0;
    left: 0;
  }

  .countdown {
    width: 460rpx;
    height: 600rpx;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -70%);
  }
}

.save-pdf {
  position: absolute;
  top: 300px;
  left: 100px;
}

.mask {
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.7);
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999999999;

  .image-tip {
    width: 100vw;
    height: 1028rpx;
    position: absolute;
    left: 50%;
    bottom: 0;
    transform: translateX(-50%);
  }

  .btn {
    width: 190rpx;
    height: 84rpx;
    border-radius: 16rpx;
    border: 2rpx solid #FFFFFF;
    text-align: center;
    line-height: 84rpx;
    color: #fff;
    position: absolute;
    left: 50%;
    bottom: 100rpx;
    transform: translateX(-50%);
    z-index: 1;
  }
}

:deep(.uni-popup__info) {
  color: #333;
  font-size: 36rpx;
}

:deep(.uni-dialog-content-text) {
  font-size: 32rpx;
  color: #1C1C1E;
}

:deep(.uni-dialog-button-text) {
  color: #08CB8F;
}
</style>
